package models

import (
	"gowww/comeon/config/dev"
)

type Menu struct {
	Id        int64  `json:"id" gorm:"column:id;primary_key;AUTO_INCREMENT;comment:'id'"`
	ParentId  uint64 `json:"parentId" gorm:"column:parent_id"`
	Name      string `json:"name" gorm:"column:name;type:char(10)"`
	Layout    string `json:"layout" gorm:"column:layout;type:varchar(20)"`
	Path      string `json:"path" gorm:"column:path;type:varchar(255)"`
	Status    int    `json:"status" gorm:"column:status;type:tinyint(1);default:1"`
	CreatedAt int64  `json:"createdAt" gorm:"column:created_at"`
	UpdatedAt int64  `json:"updatedAt" gorm:"column:updated_at"`
}

func (Menu) TableName() string {
	return "sy_menu"
}

//
//  Add
//  @Description:
//  @receiver m
//  @return bool
//
func (m *Menu) Add() int64 {

	dev.DB.Debug().Select("Name", "ParentId", "Layout", "Path", "Status").Create(&m)
	return m.Id

}

func getPageSize(currentPage, pageSize int) (int, int) {
	if currentPage == 0 {
		currentPage = 1
	}
	if pageSize == 0 {
		pageSize = 10
	}
	return currentPage, pageSize
}

//
//  MenuIncludeChildren
//  @Description: 菜单栏
//
type MenuIncludeChildren struct {
	Id       int64                  `json:"id"`
	ParentId uint64                 `json:"parentId"`
	Name     string                 `json:"name"`
	Layout   string                 `json:"layout"`
	Path     string                 `json:"path"`
	Status   int                    `json:"status"`
	Children []*MenuIncludeChildren `json:"children"`
}

//
//  GetMenuList
//  @Description:菜单列表
//  @receiver menu
//  @param currentPage
//  @param pageSize
//  @return uint64
//  @return []*MenuIncludeChildren
//  @return error
//
func (menu *MenuIncludeChildren) GetMenuList(currentPage, pageSize int) (uint64, []*MenuIncludeChildren, error) {
	menus := make([]*MenuIncludeChildren, 0)
	query := dev.DB.Table("sy_menu").Where("parent_id = ? and status = ?", 0, STATUS_ON)
	if menu.Name != "" {
		query = query.Where("name = ?", menu.Name)
	}
	var count uint64
	query = query.Count(&count)
	if count > 0 {
		page, size := getPageSize(currentPage, pageSize)
		offset := (page - 1) * size
		if err := query.Limit(size).Offset(offset).Order("created_at desc").Find(&menus).Error; err != nil {
			return count, menus, err
		}
		for idx, _ := range menus {
			menus[idx].Children = GetMenuData(menus[idx].Id)
		}
	}
	return count, menus, nil
}

//
//  GetMenuData
//  @Description:
//  @param parentId
//  @return []*MenuIncludeChildren
//
func GetMenuData(parentId int64) []*MenuIncludeChildren {
	m := make([]*MenuIncludeChildren, 0)
	dev.DB.Debug().Table("sy_menu").Where("parent_id = ? and status = ?", parentId, STATUS_ON).Find(&m)
	return m
}
